#include "ForUSBDriver.h"

HANDLE CompletionPort;
DWORD WINAPI WorkerThread(LPVOID CompletionPortID)
{
	HANDLE r, hDevice;
	DWORD BytesTransferred, dwBytesReturned;	
	PPACKET pPacket;
	PHANDLE_DATA pHandleData; 

	if ((pHandleData = (PHANDLE_DATA) GlobalAlloc(GPTR,sizeof(HANDLE_DATA))) == NULL)
	        cout<<("GlobalAlloc() error %d\n", GetLastError());
	
	if ((pPacket = (PPACKET) GlobalAlloc(GPTR,sizeof(PACKET))) == NULL)
		cout<<("GlobalAlloc() error %d\n", GetLastError());

	ZeroMemory(&(pPacket->Overlapped), sizeof(OVERLAPPED));
	
	if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1)) == NULL)
	{
		cout<<( "Error CreateIoCompletionPort: %d\n", GetLastError());
		return 0;
	}
	hDevice = CreateFile(L"\\\\.\\ControlUsbSniffer", NULL, 0, NULL, 
							OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
	
    if(hDevice == INVALID_HANDLE_VALUE)
	{
		cout<<"fuck";
	}

	if (CreateIoCompletionPort(hDevice, CompletionPort, (ULONG_PTR)pHandleData, 1) == NULL)
	{
		cout<<("CreateIoCompletionPort Error %d\n", GetLastError());
	}

	DeviceIoControl(hDevice, IOCTL_SET_TRANSPORT_PACKET, NULL, 0, pPacket->Buffer, SIZE_OF_PACKET, 
								NULL, &(pPacket->Overlapped));

	
	while(TRUE)
	{
		if (GetQueuedCompletionStatus(CompletionPort, &BytesTransferred,
			(LPDWORD)&pHandleData, (LPOVERLAPPED *) &pPacket, INFINITE) == 0)
		{
			cout<<("GetQueuedCompletionStatus error! %d!\n", GetLastError());
			continue;
		}
		if(pHandleData == NULL)
			break;
		//Function from lib, now just print message
		ProcessIncomingBuffer(pPacket->Buffer, SIZE_OF_PACKET);

		DeviceIoControl(hDevice, IOCTL_SET_TRANSPORT_PACKET, NULL, 0, pPacket->Buffer, SIZE_OF_PACKET, 
			NULL, &(pPacket->Overlapped));
	}
	CloseHandle(hDevice);
	if(GlobalFree(pPacket)||GlobalFree(pHandleData))
			cout<<("GlobalFree() error %d\n", GetLastError());
	return 0;
}